import axios from 'axios';
import qs from 'qs';
import {
  Message,
  Loading
} from 'element-ui';

import {
  sessionStorage
} from "@/utils";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 1000 * 60 * 5
});

// 处理频繁请求
let pending = [];
let CancelToken = axios.CancelToken;
let removePending = config => {
  for (let p in pending) {
    if (pending[p].u === config.url + '&' + config.method) {
      pending[p].f();
      pending.splice(p, 1);
    }
  }
};

// 拦截请求
let loading = null;
service.interceptors.request.use(
  config => {
    // 频繁请求
    removePending(config);
    config.cancelToken = new CancelToken(c => {
      pending.push({
        u: config.url + '&' + config.method,
        f: c
      });
    });
    // 头信息配置
    config.headers.post['Content-Type'] = 'application/json';
    let user = sessionStorage.get("USER") || {};
    if (user.token) {
      config.headers['x-access-token'] = user.token;
    }
    // fix:ie里get请求被缓存
    if ("ActiveXObject" in window && config.method === 'get') {
      config.params = Object.assign(config.params, {
        timestamp: Date.now()
      })
    }
    // 提示
    loading = Loading.service({
      lock: true,
      text: "Loading...",
      background: "rgba(0, 0, 0, 0.7)"
    })
    return config;
  },
  err => {
    loading.close();
    return Promise.reject(err);
  }
);

// 拦截响应
service.interceptors.response.use(
  res => {
    removePending(res.config);
    // 提示
    loading.close();
    if (res.data.code !== 0) {
      // 无效token
      if (res.data.code === 402) {
        location = "/";
      } else {
        Message.error(res.data.msg || '服务异常，请联系管理员');
        return Promise.reject();
      }
    }
    return res.data;
  },
  err => {
    loading.close();
    return Promise.reject(err);
  }
);

/**
 * post请求可能有query，统一拼接方法
 * @param path  {string}        请求地址
 * @param param {object}        请求参数
 * @property body {object}      post请求body
 * @property query {object}     post请求query
 */
function paramsQuery(path, param = {}) {
  let params = Object.assign({
    body: {},
    query: {}
  }, param);
  let query = qs.stringify(params.query);
  if (query) {
    path = `${path}?${query}`;
  }
  return {
    body: params.body,
    path
  };
}

export {
  service,
  paramsQuery
};